﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using Project.Core.Api.Common.Base;
using Project.Core.Api.Controllers.System.IPermission.Dto;
using Project.Core.Common;
using Project.Core.IServices.System;
using Project.Core.Model.System;
using Project.Core.Api.AutoMapper;

namespace Project.Core.Api.Controllers.System.IPermission
{
    /// <summary>
    /// 授权Controller
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [Authorize]
    public class PermissionController : Controller
    {
        #region 依赖注入属性
        readonly IUserPermissionService _userPermissionService;
        readonly IMenuService _menuService;
        readonly IMapper _mapper;
        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        public PermissionController(IUserPermissionService userPermissionService, IMenuService menuService, IMapper mapper)
        {
            _userPermissionService = userPermissionService;
            _menuService = menuService;
            _mapper = mapper;
        }
        #endregion

        #region 依据RoleID获取此角色的菜单权限
        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="Condition">条件</param>
        /// <returns></returns>
        [HttpPost]
        [Route("GetUserPermissionByRoleID")]
        public async Task<IActionResult> GetUserPermissionByRoleID([FromBody]PermissionCondition Condition)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var list = await _userPermissionService.Query(x => x.RoleID == Condition.RoleID && x.IsValid);
                    List<PermissionDto> dtoList = new List<PermissionDto>();
                    PermissionDto dto = null;
                    PermissionDto childdto = null;
                    foreach (var item in list)
                    {
                        var entity = await _menuService.Find(x => x.Id == item.MenuId && x.Belong == 0 && x.IsValid);
                        if (entity != null)
                        {
                            dto = new PermissionDto();
                            dto.MenuName = entity.MenuName;
                            dto.MenuId = entity.Id;
                            dto.MenuPath = entity.MenuPath;
                            dto.MenuIcon = entity.MenuIcon;
                            dto.Operation = entity.Operation?.Split(',', StringSplitOptions.None).ToList();
                            var children = await _menuService.Query(x => x.IsValid && x.Belong == entity.Id);
                            List<PermissionDto> childList = new List<PermissionDto>();
                            foreach (var child in children)
                            {
                                childdto = new PermissionDto();
                                childdto.MenuName = child.MenuName;
                                childdto.MenuId = child.Id;
                                childdto.MenuPath = child.MenuPath;
                                childdto.MenuIcon = child.MenuIcon;
                                childdto.Operation = child.Operation?.Split(',', StringSplitOptions.None).ToList();
                                childList.Add(childdto);
                            }

                            dto.Children = childList;
                            if (entity.Belong == 0)
                            {
                                dtoList.Add(dto);
                            }
                        }
                    }
                    if (list != null && list.Count > 0)
                    {
                        //var dtoList = _mapper.Map<UserPermissionDto>(list.FirstOrDefault());
                        //dtoList.Children = _mapper.Map<List<DetailPermissionDto>>(list.FirstOrDefault().Children);
                        //for (int i = 0; i < dtoList.Children.Count; i++)
                        //{
                        //    dtoList.Children[i].Id = list.FirstOrDefault().Children[i].Id;
                        //}

                        return Ok(new ReturnMsg
                        {
                            Data = dtoList,
                            Msg = "获取角色权限列表成功!",
                            Success = true,
                            Total = list.Count(),
                        });
                    }
                    return Ok(new ReturnMsg
                    {
                        Data = null,
                        Msg = "获取角色权限列表成功!",
                        Success = true,
                        Total = 0,
                    });
                }
                catch (Exception e)
                {
                    return Ok(new ReturnMsg
                    {
                        Data = null,
                        Msg = "获取角色权限列表失败!",
                        Success = false,
                        Total = 0,
                    });
                }
            }
            else
            {
                return Ok(new ReturnMsg
                {
                    Data = null,
                    Msg = "参数错误!",
                    Success = false,
                    Total = 1,
                });
            }
        }
        #endregion

        #region 添加用户权限 更新用户权限 删除用户权限
        /// <summary>
        /// 添加用户权限 更新用户权限 删除用户权限
        /// </summary>
        /// <param name="baseOperation">参数</param>
        /// <returns></returns>
        [HttpPost]
        [Route("Operation")]
        public async Task<ActionResult> Operation([FromBody]BaseOperation<UserPermissionDto> baseOperation)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    // var Entity = baseOperation.Dto.Mapping<UserPermission>();
                    //var Entity = _mapper.Map<UserPermission>(baseOperation.Dto);
                    //Entity.Children = _mapper.Map<List<Permission>>(baseOperation.Dto.Children);
                    //for (int i = 0; i < baseOperation.Dto.Children.Count; i++)
                    //{
                    //    Entity.Children[i].Children = _mapper.Map<List<Permission>>(baseOperation.Dto.Children[i].Children);
                    //}
                    //foreach (var item in baseOperation.Dto.Children)
                    //{
                    //    foreach (var item1 in Entity.Children)
                    //    {
                    //        item1.Children = _mapper.Map<List<Permission>>(item.Children);
                    //    }
                    //}
                    // var Entity = _mapper.Map<UserPermissionDto, UserPermission>(baseOperation.Dto);

                    bool result = false;

                    string msg = "";

                    switch (baseOperation.Action)
                    {
                        case OperationEnum.add:
                            // result = await _userPermissionService.Add(baseOperation.Dto) > 0;
                            msg = "添加";
                            break;
                        case OperationEnum.update:
                            // result = await _userPermissionService.Update(baseOperation.Dto);
                            msg = "更新";
                            break;
                        case OperationEnum.delete:
                            baseOperation.Dto.IsValid = false;
                            // result = await _userPermissionService.Delete(baseOperation.Dto);
                            msg = "删除";
                            break;
                    }
                    return Ok(new ReturnMsg
                    {
                        Data = result ? baseOperation.Dto : null,
                        Msg = msg + "用户权限" + (result ? "成功" : "失败") + "!",
                        Success = result,
                        Total = result ? 1 : 0,
                    });
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
            else
            {
                return Ok(new ReturnMsg
                {
                    Data = null,
                    Msg = "参数错误!",
                    Success = false,
                    Total = 1,
                });
            }
        }
        #endregion

        #region 获取写死的菜单
        /// <summary>
        /// 获取Permission列表
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [Route("getPermission")]
        public IActionResult getPermission()
        {
            // model的属性如果不加验证相关的特性，ModelState.IsValid会永远为true；如果加了验证相关的特性，不满足验证规则时，ModelState.IsValid为false.
            if (ModelState.IsValid)//判断是否合法
            {
                List<PermissionDto> list = new List<PermissionDto>();
                List<PermissionDto> childrenList = new List<PermissionDto>();
                List<PermissionDto> cchildrenList = new List<PermissionDto>();

                PermissionDto dto = new PermissionDto();

                // 第一层
                dto.MenuName = "订单管理";
                dto.MenuPath = "/order";

                PermissionDto dtochild1 = new PermissionDto();
                PermissionDto dtochild2 = new PermissionDto();
                PermissionDto dtochild3 = new PermissionDto();
                PermissionDto dtocchild1 = new PermissionDto();
                PermissionDto dtocchild2 = new PermissionDto();

                PermissionDto dto2 = new PermissionDto();

                dto2.MenuName = "订单列表";
                dto2.MenuPath = "/order-list";

                dtocchild1.MenuName = "生产列表";
                dtocchild1.MenuPath = "/production-list";

                dtocchild2.MenuName = "审核管理";
                dtocchild2.MenuPath = "/review-manage";


                // cchildrenList.Add(dtocchild1);
                cchildrenList.Add(dtocchild2);


                dtochild1.MenuName = "生产管理";
                dtochild1.MenuPath = "/product-manage";
                dtochild1.Children = cchildrenList;

                dtochild3.MenuName = "退货管理";
                dtochild3.MenuPath = "/return-goods";

                childrenList.Add(dtochild1);
                childrenList.Add(dto2);
                //childrenList.Add(dtochild3);

                dto.Children = childrenList;

                PermissionDto dto1 = new PermissionDto();
                List<PermissionDto> childrenList1 = new List<PermissionDto>();
                PermissionDto dtochild4 = new PermissionDto();
                PermissionDto dtochild5 = new PermissionDto();
                dtochild4.MenuName = "产品列表";
                dtochild4.MenuPath = "/production-list";

                dtochild5.MenuName = "产品分类";
                dtochild5.MenuPath = "/review-manage";

                childrenList1.Add(dtochild4);
                childrenList1.Add(dtochild5);

                dto1.MenuName = "产品管理";
                dto1.MenuPath = "/goods";
                // dto1.children = childrenList1;


                PermissionDto dto3 = new PermissionDto();
                List<PermissionDto> childrenList2 = new List<PermissionDto>();
                PermissionDto dtochild6 = new PermissionDto();
                PermissionDto dtochild7 = new PermissionDto();
                PermissionDto dtochild8 = new PermissionDto();
                PermissionDto dtochild9 = new PermissionDto();
                PermissionDto dtochild10 = new PermissionDto();
                dto3.MenuName = "系统管理";
                dto3.Children = childrenList2;
                dtochild6.MenuName = "菜单管理";
                dtochild7.MenuName = "角色管理";
                dtochild8.MenuName = "组织机构管理";
                dtochild9.MenuName = "分配权限";
                dtochild10.MenuName = "用户管理";
                childrenList2.Add(dtochild6);
                childrenList2.Add(dtochild8);
                childrenList2.Add(dtochild7);
                childrenList2.Add(dtochild9);
                childrenList2.Add(dtochild10);


                list.Add(dto);
                list.Add(dto3);
                // list.Add(dto1);




                return Ok(new ReturnMsg
                {
                    Data = list,
                    Msg = "成功",
                    Success = true,
                    Total = 0,
                });

            }

            return BadRequest();
        }
        #endregion
    }
}